package com.zhangmeng.tools.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import cn.hutool.socket.aio.AioClient;
import cn.hutool.socket.aio.AioServer;
import cn.hutool.socket.aio.AioSession;
import cn.hutool.socket.aio.SimpleIoAction;
import com.zhangmeng.tools.utils.AlertUtils;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-05-06 10:38
 */
@Slf4j
public class AioServerSocketController {

    @FXML
    public TextArea content;

    @FXML
    public TextField input;

    @FXML
    public Button send;

    @FXML
    public TextField port;

    public Button start_server;

    public Button close_server;

    private AioServer aioServer;

    private AioSession aioSession;

    private void appendMsg(String msg) {
        content.appendText(System.lineSeparator());
        content.appendText(msg);
    }

    @FXML
    public void initialize() {

        port.setText("8083");

        start_server.setOnAction(event -> {
            content.setText(null);
            if (port.getText().length() == 0) {
                AlertUtils.alert_warning("端口不能为空");
                return;
            }
            new Thread(() -> {
                aioServer = new AioServer(Integer.parseInt(port.getText())) {
                    @Override
                    public void start(boolean sync) {
                        log.debug("Aio Server started, waiting for accept.");
                        appendMsg("服务启动成功============================================================================================");
                        // 接收客户端连接
                        accept();
                        if (sync) {
                            ThreadUtil.sync(this);
                        }
                    }
                };
                aioServer.setIoAction(new SimpleIoAction() {
                    @Override
                    public void accept(AioSession session) {
                        aioSession = session;
                        String msg = "【客户端】：{} 连接。" + session.getRemoteAddress();
                        appendMsg(msg);
                        session.write(BufferUtil.createUtf8("=== Welcome to Hutool socket server. ==="));
                    }

                    @Override
                    public void doAction(AioSession session, ByteBuffer data) {
                        appendMsg("========>服务端接收"  + new Date()  + "=======>:"  + StrUtil.utf8Str(data));
                        if (data.hasRemaining()) {
                        } else {
                            session.read();
                        }
                    }
                }).start(true);
            }).start();
        });

        send.setOnAction(event -> {
            send();
        });

        close_server.setOnAction(event -> {
            if (aioServer.isOpen()) {
                aioServer.close();
                appendMsg("服务关闭成功============================================================================================");
            }
        });
    }

    private void send() {
        if (input.getText().length() == 0) {
            AlertUtils.alert_warning("发送的内容不能为空");
            return;
        }
        String msg = input.getText();
        aioSession.write(ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)));
        appendMsg("========>服务端发送"  + new Date()  + "=======>:" + msg );
    }
}
